<template>
  <div class="upload">
    <div @click="showActionSheet" class="upload-file">
      <span>{{ title }}</span> <img class="upl_img" alt src="@/assets/img/fujian.png"/>
    </div>

    <input
        ref="fileInput"
        type="file"
        accept="image/*"
        style="display: none"
        @change="handleFileChange"
    />

    <div class="uploadcontent" v-if="showUpload">
      <div class="filerows" v-for="(item, index) in fileList" :key="index">
           <span class="filename" @click="click_preview(item)">{{
               item.fileName
             }}</span>
        <img class="uplimg" @click="deleteFile(index)" src="@/assets/img/2.png" v-if="showUpload"/>
        <span class="operation" v-if="!showUpload" @click="click_preview(item)">查看</span>
      </div>
    </div>
    <!--    <div class="uploadcontent" v-if="!showUpload">-->
    <!--      <div class="filerows2" v-for="(item, index) in fileList" :key="index">-->
    <!--        <span class="filename" @click="click_preview(item)">{{-->
    <!--            item.fileName-->
    <!--          }}</span>-->
    <!--        <img class="uplimg" @click="deleteFile(index)" src="@/assets/img/2.png" v-if="showUpload"/>-->
    <!--        <span class="operation" v-if="!showUpload" @click="click_preview(item)">查看</span>-->
    <!--      </div>-->
    <!--    </div>-->
    <div class="preview-cover" v-if="filePreviewShow">
      <img :src="uri"/>
    </div>

    <van-action-sheet v-model="show" cancel-text="取消"
                      :actions="actions" @select="onSelect"/>

    <take-photo ref="takePhoto" v-show="showCamera" @closeCamera="showCamera=false" @getImg="getImg"></take-photo>

  </div>
</template>

<script>

import {getAction, uploadAction, postAction} from "@/api/manage";
import {apiBaseUrlDownload, apiBaseUrlUpload} from "@/utils/request";
import {ImagePreview} from "vant";
import takePhoto from "@/components/takePhoto.vue";

export default {
  props: {
    id: String,
    fileUrl: Array,
    type: Number,
    isDone: Boolean,
    title: {
      type: String,
      default: '附件'
    },
    fileType: {
      type: String,
      default: "",
    }, //定义图标样式不传
    fileIds: {
      type: String,
      default: "",
    }, //父子组件需要传递的值
    titleName: {
      type: String,
      default: "附件",
    },
    maxCount: {
      type: Number,
      default: 5,
    }, //最大上传数量
    multiple: {
      type: Boolean,
      default: true,
    }, //是否展示上传区域 //开启多选
    iconType: {
      type: String,
      default: "",
    }, //定义上传组件图标 空时默认  换图标自己在slot里加
    showUpload: {
      type: Boolean,
      default: true,
    }, //是否展示上传区域
  },
  components: {takePhoto},
  data() {
    return {
      apiBaseUrlDownload,
      showCamera: false,
      selectedPhoto: '',
      photoList: [],
      show: false,
      actions: [
        {name: '拍照'},
        {name: '从相册中选择'},
        {name: '选择本地文件'},
      ],
      filePreviewShow: false,
      uri: "",
      fileList: [],
    }
  },
  watch: {
    fileIds: {
      handler(newVal, oldVal) {
        if (this.showUpload == false) {
          this.initFileList();
        } else {
          if (newVal == "") {
            this.fileList = [];
          } else {
            this.initFileList();
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // deleteFile(idx) {
    //   this.photoList.splice(idx, 1)
    // },
    showActionSheet() {
      this.show = true
    },
    onSelect(option) {
      if (option.name === '拍照') {
        this.showCamera = true
        this.$refs.takePhoto.getCamera()
      } else if (option.name === '从相册中选择') {
        this.choosePhoto();
      } else if (option.name === '选择本地文件') {
        this.chooseFile();
      }
      this.show = false
    },
    getImg(blob) {
      this.showCamera = false
      let formData = new FormData(); //构造一个 FormData，把后台需要发送的参数添加
      formData.append("file", blob);
      formData.append("biz", "photo.jpg");
      uploadAction("/jksaas-produce/produce/sys/common/upload2", formData).then((res) => {
        if (res.success) {
          this.fileList.push(res.result);
          this.fileChange();
        }
      });
    },
    takePhoto() {
      // 调用前置摄像头拍照
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({video: {facingMode: 'environment'}})
            .then((stream) => {
              // 在这里处理拍照逻辑
              console.log(stream)
              // 在获取到摄像头的视频流后，创建一个 video 元素来显示摄像头的实时画面
              const video = document.createElement('video');
              video.srcObject = stream;
              video.autoplay = true;

              // 创建一个 canvas 元素来进行截图
              const canvas = document.createElement('canvas');
              const context = canvas.getContext('2d');

              let that = this;

              // 获取拍照按钮元素
              const captureButton = document.getElementById('captureButton');

              // 在按钮点击事件中进行拍照操作
              captureButton.addEventListener('click', () => {
                // 当用户点击拍照时，将视频画面绘制到 canvas 上，并获取图像数据
                context.drawImage(video, 0, 0, canvas.width, canvas.height);
                canvas.toBlob(function (blob) {
                  console.log(blob)
                  // 在这里执行上传操作，将 blob 对象发送到服务器
                  let formData = new FormData();
                  formData.append("file", blob);
                  formData.append("biz", "photo.jpg");
                  uploadAction("/jksaas-produce/produce/sys/common/upload2", formData).then((res) => {
                    if (res.success) {
                      // 处理上传成功的逻辑
                    }
                  });

                }, 'image/jpeg'); // 上传的文件类型，这里假设为 JPEG 图片

                // 停止摄像头的视频流
                stream.getTracks().forEach((track) => {
                  track.stop();
                });
              });

              // 将视频元素添加到页面上
              document.body.appendChild(video);

              console.log(this.photoList)

              // 在 video 元素加载完成后，调用 takePhoto 方法进行拍照
              video.addEventListener('loadedmetadata', () => {
                // 自动播放视频
                video.play();
              });

              // 在 video 元素出错时，显示错误信息
              video.addEventListener('error', (event) => {
                console.error('摄像头打开失败:', event);
              });
            })
            .catch((error) => {
              // 处理错误
            });
      }
    }
    ,
    base64ToBinary(base64) {
      const base64Data = base64.replace(/^data:image\/jpeg;base64,/, ''); // 移除开头的 "data:image/jpeg;base64,"
      const binaryString = atob(base64Data);
      const length = binaryString.length;
      const bytes = new Uint8Array(length);

      for (let i = 0; i < length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }

      return bytes;
    }
    ,

    choosePhoto() {
      // 触发选择手机照片
      this.$refs.fileInput.click();
    }
    ,
    chooseFile() {
      // 触发选择本地文件
      this.$refs.fileInput.click();
    }
    ,
    handleFileChange(event) {
      const file = {
        file: event.target.files[0]
      }
      console.log(file, event)
      // 在这里处理选择的文件
      this.afterRead(file)
    }
    ,


    initFileList() {
      console.log("fileIds1" + this.fileIds);
      let ids = [];
      ids = this.fileIds ? this.fileIds.split(",") : [];
      this.fileList = [];
      ids.forEach((item) => {
        let params = {id: item};
        getAction("/jksaas-produce/produce/public/pubAttachmentFile/queryById", params).then((res) => {
          if (res.success) {
            // console.log("sssss"+that_.fileList)
            let obj = res.result;
            obj.uri = "/sys/common/static/" + obj.uri;
            // console.log(obj.uri);
            this.fileList.push(obj);
          }
        });
      });
    }
    ,
// 文件超过大小
    onOversize(file) {
      console.log(file);
      this.$toast("文件大小不能超过 10M");
    }
    ,
    /**文件上传 */
    afterRead(file) {
      console.log(file)
      let that_ = this;

      // 判断上传的文件大小是否超过要求
      const maxSizeInBytes = 10 * 1024 * 1024; // 10MB的最大文件大小（以字节为单位）

      for (let i = 0; i < this.fileList.length; i++) {
        const file = this.fileList[i];
        if (file.size > maxSizeInBytes) {
          this.$toast("文件大小不能超过 10M");
          return;
        }
        // 文件大小符合要求，继续处理文件
      }

      // 判断最多上传的文件个数
      if (this.fileList.length >= this.maxCount && this.maxCount != "-1") {
        this.$toast("最多上传" + this.maxCount + "个文件");
        return;
      }

      let formData = new FormData(); //构造一个 FormData，把后台需要发送的参数添加
      formData.append("file", file.file);
      formData.append("biz", "temp");
      uploadAction("/jksaas-produce/produce/sys/common/upload2", formData).then((res) => {
        if (res.success) {
          that_.fileList.push(res.result);
          that_.fileChange();
        }
      });
    }
    ,
    /**文件删除 */
    beforeDelete(file, detail) {
    }
    ,
    /* 文件下载 */
    click_preview(item) {
      let reg = /\w*(?=\/)/;
      if (item.mediaType.match(reg)[0] == "image") {
        this.uri = apiBaseUrlDownload + 'jksaas-mgt/mgt' + item.uri;
        console.log(this.uri);
        console.log(item.mediaType.match(reg)[0], item.mediaType);
        ImagePreview({
          images: [this.uri],
          startPosition: 0,
          closeable: true,
        });
      } else {
        location.href = apiBaseUrlDownload + item.uri;
      }
    }
    ,
    /* 删除文件*/
    deleteFile(index) {
      // console.log(index);
      this.fileList.splice(index, 1);
      //    arr.splice(arr.findIndex(item => item.id === data.id), 1)
      this.fileChange();
    }
    ,
    fileChange() {
      let ids = "";
      this.fileList.forEach((item, index) => {
        // console.log(item);
        if (index == this.fileList.length - 1) {
          ids = ids + item.id;
        } else {
          ids = ids + item.id + ",";
        }
      });
      this.$emit("fileChange", ids);
    }
    ,
  }
}
</script>

<style lang="scss" scoped>

/deep/ .van-action-sheet {
  z-index: 999999 !important;
}

.upload-file {
  display: flex;
  justify-content: space-between;
  padding: 34px;
}

.upl_img {
  width: 36px;
  height: 36px;
}

.upload {
  // margin-bottom: 0.1rem;
  .uploadtitle {
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 34px;

    .title {
      font-size: 30px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
    }
  }

  .uploadcontent {
    background: #ffffff;

    .filerows {
      display: flex;
      justify-content: space-between;
      padding: 34px;

      .operation {
        font-size: 28px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #1e8df5;
      }
    }

    .filerows2 {
      display: flex;
      justify-content: space-between;
      padding-bottom: 30px;

      .operation {
        font-size: 28px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #1e8df5;
      }
    }
  }
}

.uplimg {
  width: 36px;
  height: 36px;
}

.filename {
  width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

#captureButton {
  position: fixed;
  bottom: 30px;
  left: 50%;
  right: 50%;
  background-color: #333;
  color: #fff;
  text-align: center;
}

#videoContainer {
  position: relative;
  width: 100vw;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 宽高比 */
}

#videoElement {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
}
</style>
